package de.westranger.forex.trading.analysis;


public final class LinearRegression {

	public static double[] computeRegression(final double[] xValues, final double[] yValues) {
		if (xValues.length != yValues.length) {
			throw new IllegalArgumentException("array lenghts do not match: " + xValues.length + " != " + yValues.length);
		} else {
			double meanX = 0.0;
			double meanY = 0.0;

			for (int i = 0; i < xValues.length; i++) {
				meanX += xValues[i];
				meanY += yValues[i];
			}

			meanX /= xValues.length;
			meanY /= yValues.length;
			
			double varX = 0.0;
			double cov = 0.0;

			for (int i = 0; i < xValues.length; i++) {
				final double var = xValues[i] - meanX;
				varX += var * var;
				cov += var * (yValues[i] - meanY);
			}

			final double b = cov / varX;
			final double a = meanY - b * meanX;

			return new double[] { a, b };
		}
	}
	
	public static double linearFunction(final double xValue, final double[] funcParameter) {
		return funcParameter[0] + funcParameter[1] * xValue;
	}
	
	public static double[] normalize(final double[] xValues, final double[] yValues, final double[] funcParameter) {
		final double[] result = new double[xValues.length];

		for (int i = 0; i < xValues.length; i++) {
			result[i] = yValues[i] - linearFunction(xValues[i], funcParameter);
		}

		return result;
	}

	public static String printFunction(final double[] funcParameter) {
		return funcParameter[0] + " + " + funcParameter[1] + "x";
	}
}
